#pragma once

#pragma warning(push)
#pragma warning(disable:4244)
#include <boost/thread.hpp>
#pragma warning(pop)

#include "Business/Customer.h"
#include "Utils/FastBlockQueue.h"
#include "Repository/DealingRepository.h"
#include "Repository/CancellationRepository.h"
#include "Business/QueueContext.h"
#include "Service/MarketStorage.h"
#include "Utils/TimeoutNotifier.h"

struct PersistVariety
{
	char prefix[5];
	int minPirceUnit;
	int multiple;
	double margin;
	double percentOpenCharge;
	double percentOffsetTodayCharge;
	double percentOffsetCharge;
	double fixedOpenCharge;
	double fixedOffsetTodayCharge;
	double fixedOffsetCharge;
};


class SendRequestThread;
class AbstractApiConnection;
class ThreadManager
{
public:
	ThreadManager(std::vector<PersistVariety> const& varietys, char const* seatNo, char const* customerNo, char const* password);
	~ThreadManager();
	ContractCodes const& GetContractCodes() const { return m_contractCodes; }
	std::map<std::string,int> const& GetContractMap() const { return m_contractMap; }
	HANDLE GetQuitHandle() const { return m_hQuit; }
	QueueContext& GetQueueContext() { return m_queueContext; }
	Customer& GetCustomer() { return m_customer; }
	MarketStorage& GetMarketStorage() { return m_marketStorage; }
	DealingRepository& GetDealingRepository() { return m_dealingRepository; }
	CancellationRepository& GetCancellationRepository() { return m_cancellationRepository; }
	TimeoutNotifier& GetTimeoutNotifier() { return m_timeoutNotifier; }
	ContractMatcheres& GetContractMatcheres() { return m_contractMatcheres; }

	int GetContract(char const* code) const;
	char const* GetCode(int contract) const;
	void SubscribeMarket(char const* code);
	void SubscribeMarket(int contract);
	void SubscribePendingMarket(int contract);

private:
	void InitContractCodes();

	void CreateVarietys(char const* prefix, Variety &variety);
	void FillVariety(PersistVariety const& persistVariety, Variety &variety);
	void InitThread();

	AbstractApiConnection& GetConnection();
	std::vector<PersistVariety> const& m_varietys;
	ContractCodes m_contractCodes;
	std::map<std::string,int> m_contractMap;
	HANDLE m_hQuit;
	FastBlockQueue::FastBlockQueuePtr m_requestQueue;
	FastBlockQueue::FastBlockQueuePtr m_businessQueue;
	FastBlockQueue::FastBlockQueuePtr m_uiQueue;
	FastBlockQueue::FastBlockQueuePtr m_highTimerQueue;
	FastBlockQueue::FastBlockQueuePtr m_waitableTimerQueue;
	MarketStorage m_marketStorage;
	QueueContext m_queueContext;
	DealingRepository m_dealingRepository;
	CancellationRepository m_cancellationRepository;
	std::auto_ptr<boost::thread> m_businessThread;
	std::auto_ptr<boost::thread> m_sendRequestThread;
	std::auto_ptr<boost::thread> m_highTimerThread;
	std::auto_ptr<boost::thread> m_waitTimerThread;
	Customer m_customer;
	TimeoutNotifier m_timeoutNotifier;
	ContractMatcheres m_contractMatcheres;
};
